#!/usr/node/bin/node

/*
 * Copyright (c) 2015, Joyent, Inc. All rights reserved.
 *
 *
 * Outputs the network configuration from the boot-time config file
 */

var boot_file = require('/usr/node/node_modules/net-boot-config');
var dashdash = require('/usr/node/node_modules/dashdash');
var fmt = require('util').format;
var path = require('path');



var ME = path.basename(process.argv[1]);



function main() {
    var opts;
    var options = [
        {
            name: 'enabled',
            type: 'bool',
            help: 'Exit 0 if boot-time networking is enabled.'
        },
        {
            names: ['json', 'j'],
            type: 'bool',
            help: 'Output JSON.'
        },
        {
            names: ['help', 'h'],
            type: 'bool',
            help: 'Print help and exit.'
        },
        {
            name: 'nictag-rules',
            type: 'bool',
            help: 'Print nic tag rules.'
        },
        {
            name: 'routes',
            type: 'bool',
            help: 'Print routes.'
        }
    ];
    var parser = dashdash.createParser({options: options});

    try {
        opts = parser.parse(process.argv);
    } catch (parseErr) {
        console.error('%s: error: %s', ME, parseErr.message);
        process.exit(1);
    }

    if (opts.help) {
        return console.log([
            fmt('usage: %s [OPTIONS]', ME),
            '',
            'Options:',
            parser.help({includeEnv: true}).trimRight(),
            '',
            'If no options are specified, outputs config values'
        ].join('\n'));
    }

    if (opts.enabled) {
        return boot_file.enabled(function (res) {
            process.exit(res ? 0 : 1);
        });
    }

    if (opts.json || opts.routes || opts.nictag_rules) {
        return boot_file.load(function (err, config) {
            if (err) {
                return console.error(err.message);
            }

            if (opts.json) {
                console.log(JSON.stringify(config, null, 2));
                return null;
            }

            if (opts.routes) {
                for (var r in config.routes) {
                    console.log(fmt('%s %s', r, config.routes[r]));
                }

                return null;
            }

            return console.log(JSON.stringify(config.nictag_rules, null, 2));
        });
    }

    return boot_file.values(function (err, config) {
        if (err) {
            return console.error(err.message);
        }

        for (var key in config) {
            console.log(fmt('%s=%s', key, config[key]));
        }

        return null;
    });
}

main();
